package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"seichat/biz"
	"seichat/middlerware"
	"seichat/models"
	"seichat/service"
	"seichat/types"
	"strconv"
)

type CommunityHandler struct {
	comSvc service.CommunityService
}

func NewCommunityHandler(comSvc service.CommunityService) *CommunityHandler {
	return &CommunityHandler{
		comSvc: comSvc,
	}
}

func (c *CommunityHandler) RegisterRoutes(router *gin.Engine) {
	g := router.Group("/group")
	{
		g.Use(middlerware.JWT())
		g.POST("/add", c.NewGroup)
		g.GET("/list/:ownerId", c.GetCommunityListByOwnerId)
		g.POST("/join", c.JoinCommunity)
	}
}

//GetCommunityListByOwnerId 获取群聊列表

// NewGroup 新建群聊
func (c *CommunityHandler) NewGroup(ctx *gin.Context) {
	var req types.AddNewGroupReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
		return
	}
	if err := c.comSvc.CreateCommunity(context.Background(), &models.Community{
		Name:    req.Name,
		OwnerId: req.OwnerId,
		Type:    req.Type,
		Image:   req.Img,
		Desc:    req.Desc,
	}); err != nil {
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}
	ctx.JSON(http.StatusOK, biz.Success(200, "创建群成功", nil))
}

// GetCommunityListByOwnerId 获取群列表
func (c *CommunityHandler) GetCommunityListByOwnerId(ctx *gin.Context) {
	ownerIdStr := ctx.Param("ownerId")
	if ownerIdStr == "" {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
		return
	}
	ownerId, err := strconv.Atoi(ownerIdStr)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, biz.InternalServerError)
		return
	}
	list, err := c.comSvc.GetCommunityListByOwnerId(context.Background(), uint(ownerId))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}
	ctx.JSON(http.StatusOK, biz.Success(200, "获取群列表成功", list))
}

// JoinCommunity 根据群昵称添加群
func (c *CommunityHandler) JoinCommunity(ctx *gin.Context) {
	var req types.JoinCommunityReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, biz.RequestParamError)
		return
	}
	if err := c.comSvc.JoinCommunity(context.Background(), req.OwnerId, req.Cname); err != nil {
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}
	ctx.JSON(http.StatusOK, biz.Success(200, "添加群成功", nil))
}
